package com.token.handler;

import lombok.Setter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DigestUtils;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Setter
public class DefaultTokenHandler implements TokenHandler {

    private RedisTemplate redisTemplate;

    @Override
    public String generatorToken(String data) {
        return DigestUtils.sha1DigestAsHex(data);
    }

    @Override
    public Boolean isExit(String token, long timeout) {
        if (redisTemplate.hasKey(token)) {
            return false;
        } else {
            redisTemplate.opsForValue().set(token, token, timeout, TimeUnit.MILLISECONDS);
            return true;
        }
    }
}
